<?php

class TransferController extends UController
{
    /**
     * 跳转至银行充值页面
     */
    public function actionaffirmredirect()
    {
        $data        = array('success'=>0);
        $projectId   = $this->_post('projectId');
        $payNeeded   = $this->_post('payneeded');
        $bank_id     = $this->_post('bank_id',null);
        $banks = Yii::app()->params['mobileBanks'];
        $usableIds = array();
        foreach($banks as $b)
        {
            $usableIds[] = $b['code'];
        }
        if(!in_array($bank_id, $usableIds))
            $data['msg'] = '暂不支持该银行支付';
        elseif(!$payNeeded || $payNeeded<=0)
            $data['msg'] = '支付金额必须大于0';
        else
        {
            $pay_method = $this->_post('pay_method');
            $result     = $this->saveOrder($bank_id,$pay_method);
            if($result && $result->success && $result->result->tradeNo)
            {
                $data["tradeNo"]      = $result->result->tradeNo;
                $data['success']      = 1;
            }
            else
                $data['msg']    = $result->errorMsg;
        }
        $this->setResult($data);
    }

    /**
     * 保存订单
     * pay_method: 0：余额支付 3：连连支付,1：易生，2：盛富通
     * @return mixed|null
     */
    private function saveOrder($bank_id='',$pay_method = '0')
    {
        $model       = User::model();
        $user        = $model->findById($this->userId);
        $password    = $this->_post('password');
        if(!$model->checkPayPass($this->userId,$password))
        {
            return (object)array('errorMsg'=>'交易密码不正确','success'=>0);
        }
        if(!in_array($pay_method, array(0,3)))
        {
            return (object)array('errorMsg'=>'暂不支持该支付方式','success'=>0);
        }
        $cap             = $this->_post('cap',0);//余额支付金额
        $rab             = $this->_post('rab',0);//红包使用金额
        $projectId       = $this->_post('projectId');
        $amount          = $this->_post('amount'); //投资金额
        $pay_amount      = $this->_post('payneeded',0);//第三方支付金额
        $card_number     = $this->_post('card_no');//银行卡号
        $real_pay_amount = $this->_post('real_pay_amount');//实际支付金额
        /*新增投资券功能*/
        $used_coupon_amount = $this->_post('couponAmount',0);//投资券金额
        $coupon_max = Yii::app()->params['couponUseLimit'];
        if($used_coupon_amount>$coupon_max)
        {
            return (object)array('errorMsg'=>'一次投资最多可使用'.$coupon_max.'元现金券','success'=>0);
        }
        $coupon_ids         = $this->_post('coupons','');//投资券id 多个以:分隔
        if($used_coupon_amount==0)
            $coupon_ids='';
        $annual_id  = $this->_post('annual_id',0);//年化券id
        //订单来源
        $order_from = $this->_post('order_from');//订单来源 1:android 2:ios
        Yii::trace(json_encode(array_merge($_POST,array('bank_id'=>$bank_id))));
        $projectBalance = Project::model()->getBalance($projectId);
        if(in_array($pay_method, array(3,5)))
        {
            $maxAmount = Helper::getMaxPayAmount($bank_id,$pay_method);
            if($amount > $maxAmount*10000)
            {
                return (object)array('errorMsg'=>'该银行卡单笔最高可支付'.($maxAmount>=1?$maxAmount.'万':10000*$maxAmount).'元','success'=>0);
            }
        }
        if($amount > $projectBalance)
        {
            return (object)array('errorMsg'=>'投资金额不能大于项目可投金额','success'=>0);
        }
        if(!in_array($order_from, array(1,2)))
        {
            return (object)array('errorMsg'=>'order_from参数不合法','success'=>0);
        }
        if(SITEMODE !== 'DEVELOP' && $cap+$rab+$used_coupon_amount+$pay_amount != $real_pay_amount)
        {
            return (object)array('errorMsg'=>'支付总额不等于投资金额','success'=>0);
        }
        if($pay_method!=0 && $pay_amount==0)
        {
            return (object)array('errorMsg'=>'手机充值业务正在维护中','success'=>0);
        }
        $bank_code = '';
        if($bank_id)
        {
            $banks = Yii::app()->params['mobileBanks'];
            foreach($banks as $b)
            {
                if($b['code'] == $bank_id)
                {
                    $bank_code = $b['alias'];
                    break;
                }
            }
        }
        $data = array(
            'user_id'            => $this->userId,
            'user_name'          => $user->mobile,
            'transfer_id'        => $projectId,
            'invest_amount'      => $amount,
            'method'             => ($pay_amount==0)?0:$pay_method,
            'notice'             => '',
            'bank_code'          => $bank_code,
            'used_capital'       => $cap,
            'used_reward'        => $rab,
            'pay_amount'         => $pay_amount,
            'used_coupon_amount' => $used_coupon_amount,
            'coupon_ids'         => $coupon_ids,
            'order_from'         => $order_from,
            'annual_id'          => $annual_id,
            'card_no'            => $card_number,
            'real_pay_amount'    => $real_pay_amount,
        );
        $result = HttpLib::post($this->javaApi['create_order_transfer'],$data);
        return $result;
    }
    /**
     * 直接交易页面（余额支付）
     */
    public function actionaffirmdo()
    {
        $projectId = $this->_post('projectId');
        $data = array(
            'code'        => 500,
            'success'     => 0,
            'errcode'     => 0,
            'projectId'   => $projectId,
            'praise'      => 0, //是否好评
        );
        $t = $this->saveOrder('',0);
        if($t && $t->success && $t->result->tradeNo)
        {
            Yii::log('余额支付 订单号是'.$t->result->tradeNo,"info");
            $result = HttpLib::post($this->javaApi['do_transaction'],array(
                'trade_no' => $t->result->tradeNo,
                'user_id'  => $this->userId,
                'token'    => $this->token,
            ));
            if($result && $result->success)
            {
                $remote = HttpLib::get($this->javaApi['pay_invest_over'],array(
                            'trade_no' => $t->result->tradeNo,
                            'user_id'  => $this->userId,
                            'token'    => $this->token,
                ));
                if($remote->result->success)
                {
                    $data['code']         = 200;
                    $data['success']      = 1;
                    $data['projectName']  = $remote->result->projectName;
                    $data['investAmount'] = $remote->result->investAmount;
                    $data['paying']       = 0;
                    if(mt_rand(1,100)<=20)
                        $data['praise'] = 1;//20%的概率给好评
                }
                elseif($remote->result->code == 20528)
                {
                    $data['code']         = 200;
                    $data['success']      = 1;
                    $data['projectName']  = $remote->result->projectName;
                    $data['investAmount'] = $remote->result->investAmount;
                    $data['paying']       = 1;//支付中
                }
                else
                {
                    $data['errcode'] = $remote->result->code;
                    $data['msg']     = $remote->result->errorMsg;
                    if(in_array($remote->code,array('20802','20803','20804','20805')))
                    {
                        $data['msg'] = '投资劵使用失败，请重新投资';
                    }
                }
            }
            else
            {
                $data['errcode'] = $result->code;
                $data['msg']     = $result->errorMsg;
            }
        }
        else
        {
            $data['errcode'] = $t->code;
            $data['success'] = 0;
            $data['msg']     = $t->errorMsg;
        }
        $this->setResult($data);
    }
    /**
     * 设置转让
     */
    public function actionSet()
    {
        $data   = array('success'=>0);
        $password    = $this->_post('password');
        if(!User::model()->checkPayPass($this->userId,$password))
            $data['msg'] = '交易密码不正确';
        else
        {
            $params = array(
                'id'            => $this->_post('transaction_id'),
                'discount_rate' => $this->_post('discount_rate'),
                'is_discount'   => $this->_post('is_discount'),
                'season_id'     => $this->_post('season_id'),
                'start_time'    => $this->_post('start_time'),//transactionInfo里的start_time
                'end_time'      => $this->_post('end_time'),//transactionInfo里的endTime
                'transfer_code' => $this->_post('transfer_code'),//transactionInfo里的transferCode
                'total_amount'  => $this->_post('total_amount'),//转让金额
                'user_id'       => $this->userId,
            );
            $remote = HttpLib::post($this->javaApi['set_project_transfer'],$params);
            if($remote->success)
            {
                $data['success'] = 1;
            }
            else
                $data['msg'] = $remote->errorMsg;
        }
        $this->setResult($data);
    }
    /**
     * 取消转让
     */
    public function actionCancel()
    {
        $data = array('success'=>0);
        $id = $this->_post('id');
        if(!$id)
            $data['msg'] = '参数不合法';
        else
        {
            $remote = HttpLib::post($this->javaApi['cancel_project_transfer'],array('user_id'=>$this->userId,'id'=>$id));
            if($remote->success)
            {
                $data['success'] = 1;
            }
            else
                $data['msg'] = $remote->errorMsg;
        }
        $this->setResult($data);
    }
    /**
     * 查询转让进度
     */
    public function actionQueryProcess()
    {
        $data = array('success'=>0);
        $remote = HttpLib::post($this->javaApi['query_transfer_process'],array(
            'transfer_project_id' => $this->_post('transfer_project_id'),
            'user_id'             => $this->userId,
        ));
        if($remote->success)
        {
            $data['success']     = 1;
            $data['projectName'] = $remote->result->project_name;
            $data['total']       = $remote->result->total_transfer_amount;//一共转让多少
            $data['dealed']      = $remote->result->dealed_amount;//已转让多少
            $data['remain']      = $remote->result->tobe_transfered_amount;//待转让多少
            $data['list']  = array();
            foreach($remote->result->process_list as $v)
            {
                $data['list'][] = array(
                    'date'   => $v->date,
                    'amount' => $v->amount,
                );
            }
        }
        else
            $data['msg'] = $remote->errorMsg;
        $this->setResult($data);
    }
}
